package com.akino.gulimall.seckill.service.Impl;

import com.akino.common.to.mq.SeckillOrderTo;
import com.akino.common.utils.R;
import com.akino.common.vo.MemberRespVo;
import com.akino.gulimall.seckill.feign.CouponFeignService;
import com.akino.gulimall.seckill.feign.ProductFeignService;
import com.akino.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.akino.gulimall.seckill.service.SeckillService;
import com.akino.gulimall.seckill.to.SeckillSkuRedisTo;
import com.akino.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.akino.gulimall.seckill.vo.SeckillSkuVo;
import com.akino.gulimall.seckill.vo.SkuInfoVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Akino
 * @version 1.0
 */
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:session";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";
    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1.去数据库扫描需要参与秒杀的活动
        R r = couponFeignService.getLatest3DaySession();
        if (r.getCode()==0){
            List<SeckillSessionsWithSkus> sessionData = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            // 将上架的商品数据缓存到redis
            // ①缓存活动信息
            saveSessionInfos(sessionData);
            // ②缓存活动的管理那商品信息
            saveSessionSkuInfos(sessionData);
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // 1.确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            if (time>=start&&time<=end){
                // 2.获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String,String,Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List list = ops.multiGet(range);
                if (list!=null){
                    List<SeckillSkuRedisTo> collect = (List<SeckillSkuRedisTo>) list.stream().map(item -> {
                        SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                        return seckillSkuRedisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        // 1.找到所有需要参与秒杀的商品的key
        BoundHashOperations<String,String,String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (keys!=null&&keys.size()>0){
            // 正则判断
            String regx = "\\d_"+skuId;
            for (String key : keys) {
                if(Pattern.matches(regx,key)){
                    String json = ops.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    // 处理随机码
                    long current = new Date().getTime();
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    if (current>=startTime&&current<=endTime){
                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        // 1.获取当前秒杀商品的详细信息
        BoundHashOperations<String,String,String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if (StringUtils.isEmpty(json)){
            return null;
        }
        SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
        // 校验合法性
        // ->秒杀时间校验
        Long startTime = redis.getStartTime();
        Long endTime = redis.getEndTime();
        long now = new Date().getTime();
        if (now<startTime || now>endTime){
            return null;
        }
        // 时间合法，校验随机码和商品id
        String randomCode = redis.getRandomCode();
        String skuId = redis.getPromotionSessionId()+"_"+redis.getSkuId();
        if (!randomCode.equals(key) || !killId.equals(skuId)){
            return null;
        }
        // 随机码和商品id合法，验证购物数量
        BigDecimal limit = redis.getSeckillLimit();
        if (num > limit.intValue()){
            return null;
        }
        // 购物数量合法，检验是否多次购买
        String redisKey = respVo.getId()+"_"+skuId;
        // 自动过期
        long ttl = endTime - now;
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if (!ifAbsent){
            // 占位失败，多次购买
            return null;
        }
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
        try {
            semaphore.tryAcquire(num,100,TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 秒杀成功，快速下单
        String timeId = IdWorker.getTimeId();  // 订单号
        SeckillOrderTo orderTo = new SeckillOrderTo();
        orderTo.setOrderSn(timeId);
        orderTo.setMemberId(respVo.getId());
        orderTo.setNum(num);
        orderTo.setPromotionSessionId(redis.getPromotionSessionId());
        orderTo.setSkuId(redis.getSkuId());
        orderTo.setSeckillPrice(redis.getSeckillPrice());
        // 给MQ发送消息
        rabbitTemplate.convertAndSend("order-event-exchange",
                "order.seckill.order",
                orderTo);
        return timeId;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(session ->{
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime+"_"+endTime;
            //  缓存活动信息
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey){
                List<String> collect = session.getRelationSkus()
                        .stream()
                        .map(item ->
                        item.getPromotionSessionId().toString()+"_"+item.getSkuId().toString())
                        .collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,collect);
            }
        });
    }
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(session->{
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                // 设置随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                if (!redisTemplate.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())){
                    // 缓存商品
                    SeckillSkuRedisTo to = new SeckillSkuRedisTo();
                    /**
                     * 1.sku基本信息
                     * 2.sku秒杀信息
                     * 3.随机码，结束时间
                     */
                    R info = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (info.getCode()==0){
                        SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        to.setSkuInfoVo(skuInfo);
                    }
                    BeanUtils.copyProperties(seckillSkuVo,to);
                    // 设置商品的秒杀时间信息
                    to.setStartTime(session.getStartTime().getTime());
                    to.setEndTime(session.getEndTime().getTime());
                    to.setRandomCode(token);
                    // 分布式信号量（限流）
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                    String s = JSON.toJSONString(to);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),s);
                }
            });
        });
    }
}
